package net.affenkakka.shop;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.jdom.Document;
import org.jdom.Namespace;

/**
 * Servlet implementation class Login
 */
@WebServlet("/Login")
public class Login extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private Namespace ns = Namespace.getNamespace("http://www.cs.au.dk/dWebTek/2011");
       
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		// Invalidate session no matter what (User could be logged in)
		request.getSession().invalidate();
		
		Document cloudResponse = CloudManager.login(request.getParameter("username"), request.getParameter("password"));
		HttpSession session = request.getSession();
		
		if (cloudResponse != null)
		{
			if (cloudResponse.getRootElement().getName() == "loginResponse" && cloudResponse.getRootElement().getChildText("customerID") != "" && cloudResponse.getRootElement().getChildText("customerName") != "")
			{
				session.setAttribute("customerAuthed", "true");
				session.setAttribute("customerID", cloudResponse.getRootElement().getChildText("customerID", ns));
				session.setAttribute("customerName", cloudResponse.getRootElement().getChildText("customerName", ns));
				response.sendRedirect("index.jsp");
			}
		} else {
			response.getWriter().println("You typed a wrong username/password!");
			response.setHeader("Refresh", "3; URL=index.jsp");
		}
	}

}
